<?php
declare (strict_types = 1);
namespace app\course\logic\coupon\admin;

use app\admin\logic\system\Log;
use app\common\exception\LogicException;
use app\course\model\coupon\admin\Coupon;
use app\course\model\coupon\admin\CouponUser as CouponUserModel;

/**
 * 用户卡券逻辑层
 */
class CouponUser extends CouponUserModel
{
    /**
     * 获取某个卡券的用户领取情况
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-05-13
     * @return   [type]                         [description]
     */
    public function getListByCouponId(int $coupon_id)
    {
        return $this->where('coupon_id', $coupon_id)->with(['user'])->order('create_time', 'DESC')->paginate($this->getListRows());
    }

    /**
     * 给某位用户发放卡券
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-05-15
     * @param    [type]                         $coupon_id [description]
     * @param    [type]                         $user_id   [description]
     * @return   [type]                                    [description]
     */
    public function grant($coupon_id, $user)
    {
        $coupon = app(Coupon::class)->where('id', $coupon_id)->find();
        if (!$coupon) {
            throw new LogicException('卡券不存在');
        }

        // 卡券是否有剩余
        if ($coupon->count - $coupon->receive_count <= 0) {
            throw new LogicException('卡券数量不足');
        }
        // 检测用户卡券情况 - 已经领取但是未使用,不允许再发卡券
        $couponUser  = new self();
        $coupon_user = $couponUser->where('coupon_id', $coupon_id)->where('user_id', $user->id)->findOrEmpty();
     
        if (!$coupon_user->isEmpty() && $coupon_user->status != 1) {
            throw new LogicException('用户存在未使用的卡券，不能继续发放');
        }

        $this->user_id     = $user->id;
        $this->coupon_id   = $coupon_id;
        $this->coupon_type = $coupon->coupon_type;
        $this->mhm_id      = $coupon->mhm_id;
        
        if (!$this->save()) {
            throw new LogicException('卡券发放失败');
        }

        Log::write('发放卡券/' . $coupon_id . '给用户【' . $user->user_name . '/' . $user->id . '】', 'coupon_grant', 'create', true);

        return $this;

    }
}
